package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_DELAY_GROUP,
        topic = MQConstans.CREATE_ORDER,
        selectorExpression = MQConstans.CREATE_DELAY_TAG

)
public class OrderSuccessDelayMQListener implements RocketMQListener<Map> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(Map map) {
        System.out.println("进入到延时队列中");
        Long goodId = null;
        Object seckillId =map.get("seckillId");
        if(seckillId instanceof Integer){
            goodId = ((Integer) seckillId).longValue() ;
        }else if (seckillId instanceof Long){
            goodId = (Long) seckillId;
        }
        String orderNo = (String) map.get("data");
        //查看状态是否支付
        //如果未支付把状态改为超时未支付
        int count = orderInfoService.changeOrderInfoStatus(orderNo, OrderInfo.STATUS_TIMEOUT);
        if (count>0){
            //回补真实库存
            seckillGoodService.incrCount(goodId);

            //回补预库存
            seckillGoodService.syncRedisCount(goodId);

            //修改本地标识
            rocketMQTemplate.syncSend(MQConstans.CREATE_NOTIFY_DEST,goodId);

        }

    }
}
